package com.gitee.sys.filter;

import com.gitee.mybase.top.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class JwtFilter implements Filter {

    private static final Set<String> ALLOWED_PATHS = new HashSet<>(Arrays.asList("/sys/openResource","/login","/swagger","/v2","/webjars"));
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = isAllowed(ALLOWED_PATHS, path);
        if(allowedPath == true){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = request.getHeader("Authorization");

        if(StringUtils.isEmpty(token) || !JwtUtil.verify(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }

        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        response.setHeader("Authorization", "success");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }

    private boolean isAllowed(Set<String> allowedPaths, String path){
        for(String allowedPath : allowedPaths){
            if(path.startsWith(allowedPath)){
                return true;
            }
        }
        return false;
    }

}
